package pl.edu.pw.perg.compinfodb.datamodel;

import java.util.ArrayList;
import java.util.List;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import pl.edu.pw.perg.compinfodb.entities.PhysicalElement;
import pl.edu.pw.perg.compinfodb.entities.field.Field;


public class PhysicalDetailsTableModel implements TableModel,
		IPhysicalElementSelectionListener {

	private List<TableModelListener> listeners = new ArrayList<TableModelListener>();
	private String[] columnNames = { "Property", "Value" };
	private PhysicalElement selected;
	
	private List<String> fieldList = new ArrayList<String>();
	private List<String> attributeList = new ArrayList<String>();


	
	public void addTableModelListener(TableModelListener l) {
		listeners.add(l);
	}

	public Class<?> getColumnClass(int columnIndex) {
		return String.class;
	}

	public int getColumnCount() {
		return 2;
	}

	public String getColumnName(int columnIndex) {
		return columnNames[columnIndex];
	}

	public int getRowCount() {
		return fieldList.size();
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		if(columnIndex == 0)
			return fieldList.get(rowIndex);
		else if(columnIndex == 1 ){
			if(attributeList.size() == 0)
				return "";
			return attributeList.get(rowIndex);
			
		}
		throw new IndexOutOfBoundsException("Invalid row/column nr"); 
	}

	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}

	public void removeTableModelListener(TableModelListener l) {
		listeners.remove(l);

	}

	public void setValueAt(Object value, int rowIndex, int columnIndex) {
		throw new UnsupportedOperationException(
				"This table don't allows changes");

	}


	public void selectionChanged(PhysicalElement pe) {
		selected = pe;
		fieldList.clear();
		attributeList.clear();
		for (Field field : pe.getElementType().getFields()) {
			fieldList.add(field.getFieldName());
			if(pe.getAttributesMap().size() != 0)
				attributeList.add(pe.getAttribute(field.getId()).getTextValue());
		}				
//		fieldList.addAll(selected.getElementType().getFields());
		
		for (TableModelListener tml : listeners) {
			tml.tableChanged(new TableModelEvent(this));
		}

	}

}
